import * as Lark from "@larksuiteoapi/node-sdk";
import { chatCompletions } from "../spark";
import { jsonParse } from ".";

const baseConfig = {
  appId: "cli_a7b2e5241379d00d",
  appSecret: "R1b1Xrp3ODooSPpStVoVdf1TMBcdAzsV",
};

export function createLarksuit() {
  const client = new Lark.Client(baseConfig);

  const wsClient = new Lark.WSClient({
    ...baseConfig,
    loggerLevel: Lark.LoggerLevel.info,
  });

  wsClient.start({
    eventDispatcher: new Lark.EventDispatcher({}).register({
      "im.message.receive_v1": async data => {
        const {
          message: { chat_id, content },
        } = data;

        const userInput = jsonParse(content).text;
        const result = await chatCompletions(
          userInput || "不知道该说点啥，你都会什么呀？"
        );

        await client.im.v1.message.create({
          params: {
            receive_id_type: "chat_id",
          },
          data: {
            receive_id: chat_id,
            content: Lark.messageCard.defaultCard({
              title: `reply： ${JSON.parse(content).text}`,
              content: result,
            }),
            msg_type: "interactive",
          },
        });
      },
    }),
  });
}
